<?php
/**
 * 消息类
 * @author  zlc
 * @date    04/28
 */

namespace App\Common\Comp;

use App\Model\Comment;
use App\Model\CommentReply;
use App\Model\MessageCategory;
use App\Model\MessageRecord;
use App\Model\MessageInteract;
use App\Model\MessageInteractRecord;
use App\Model\User;
use App\Model\VideoDetails;
use App\Service\ImHandleService;
use App\Service\UserService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MessageComp
{
    protected $resDate;

    static $MSM_TYPE = [
        '1' => 'TIMTextElem',
        '2' => 'TIMLocationElem',
        '3' => 'TIMFaceElem',
        '4' => 'TIMCustomElem',
        '5' => 'TIMSoundElem',
        '6' => 'TIMImageElem',
        '7' => 'TIMFileElem',
        '8' => 'TIMVideoFileElem',
    ];

    static $TYPE = [
        '1' => '订单消息',
        '2' => '直播消息',
        '3' => '视频消息',
        '4' => '图片消息',
    ];


    public function __construct()
    {
        //初始化返回值
        $this->resDate = ['code' => 200, 'msg' => '', 'data' => []];
    }

    /**
     * 系统消息入库
     * @param $userId
     * @param $title
     * @param $content
     * @param $url
     * @param $type //1:抵制低俗公告,2:视频通知,3:奖杯到账通知,4:兑换通知,5:提现通知 6:课程金到账通知
     * @param $categoryId
     * @param int $cateType //消息的发送类型 1=单发 2=群发
     * @param $missId //群发消息的id
     * @param $pushTime //群发消息的推送时间
     * @param $jsonData //跳转的参数
     * @param $mechanismId //机构id
     * @return array
     */
    public function systemMessageAdd($userId, $title, $content, $url, $type, $categoryId, $cateType = 1, $missId = 0, $pushTime = 0,$jsonData='',$mechanismId=0)
    {
        try {
            $model = new MessageRecord();
            $model->user_id = $userId ?? 0;
            $model->message_title = $title ?? '';
            $model->message_content = $content ?? '';
            $model->message_url = $url ?? '';
            $model->type = $type ?? 1;
            if ($cateType == 2) {
                $model->mass_id = $missId;
            }
            $model->categroy_status = $cateType;
            $model->category_id = $categoryId;
            $model->status = 1;
            $model->mcn_id = $mechanismId;
            if ($pushTime) {
                $model->created_at = date('Y-m-d H:i:s', $pushTime);
            }
            if($jsonData){
                $model->json_data = json_encode($jsonData,JSON_UNESCAPED_UNICODE);
            }
            if (!$model->save()) {
                throw new \Exception("系统消息添加失败！！！");
            }
            $this->resDate['msg'] = '添加成功';
            return $this->resDate;
        } catch (\Exception $e) {

            $this->resDate['code'] = 50002;
            $this->resDate['msg'] = $e->getMessage();
            $systemInfo['user_id'] = $userId;
            $systemInfo['type']    = $type;
            $systemInfo['message_title'] = $title;
            $systemInfo['msg']     = $e->getMessage();
            Log::error('系统消息入库失败:'.$userId,$systemInfo);
            return $this->resDate;
        }
    }

    /**
     *  互动消息添加
     * @param $data
     * `user_id`           COMMENT '发送用户的id',
     * `receive_user_id`   COMMENT '接收者用户id',
     * `content`           COMMENT '评论内容',
     * `type`              COMMENT '类型 1=评论作品,2=赞了作品,3=赞了一级评论, 4=回复评论 5=赞了二级评论',
     * `video_id`          COMMENT '视频id',
     * `video_comment_id`  COMMENT '评论id',
     * `reply_id`          COMMENT '回复id',
     * @return array
     */
    public function interactMessageAdd($data)
    {
        $model = new MessageInteract();
        $model->user_id = $data['user_id'] ?? 0;
        $model->receive_user_id = $data['receive_user_id'] ?? 0;
        $model->content = $data['content'] ?? '';
        $model->type = $data['type'] ?? 1;
        $model->video_id = $data['video_id'] ?? 0;
        $model->video_comment_id = $data['video_comment_id'] ?? 0;
        $model->reply_id = $data['reply_id'] ?? 0;
        $ini['type'] = $model->type;
        if ($data['type'] == 2) {//赞了作品
            $ini['video_id'] = $model->video_id;
            $praisedCount = VideoDetails::where('video_id', $model->video_id)->value('praised_count');
        } elseif ($data['type'] == 3) {//赞了一级评论
            $ini['video_comment_id'] = $model->video_comment_id;
            $praisedCount = Comment::where('id', $model->video_comment_id)->value('praised_num');
        } else {
            $ini['reply_id'] = $model->reply_id;
            $praisedCount = CommentReply::where('id', $model->reply_id)->value('praised_num');
        }
        DB::beginTransaction();
        try {
            if (($data['type'] == 2) || ($data['type'] == 3) || ($data['type'] == 5)) {
                $is_flag = self::isConfirm($model->type, $model->video_id, $model->video_comment_id, $model->reply_id);
                if (!$is_flag) {//不存在添加数据
                    $model->num = $praisedCount;
                    if (!$model->save()) {
                        throw new \Exception("互动消息添加失败！！！");
                    }
                } else {
                    //更新数据
                    $saveData['user_id'] = $data['user_id'];
                    $saveData['num']     = $praisedCount;
                    $saveData['created_at'] = date('Y-m-d H:i:s', time());
                    $saveData['status']     = 1;
                    $message_arr = MessageInteract::query()->where($ini)->update($saveData);
                    if ($message_arr === false) {
                        Log::info('互动消息更新失败-用户-'.$data['user_id'],$saveData);
                        throw new \Exception("互动消息更新失败！！！");
                    }
                    if ($praisedCount == 0) {
                        self::delConfirm($model->type, $model->video_id, $model->video_comment_id, $model->reply_id);
                    }
                }
            } else {
                $praisedCount = 1;
                $model->num = 1;
                if (!$model->save()) {
                    throw new \Exception("互动消息添加失败！！！");
                }
            }
            if($praisedCount){
                $contentStr = UserService::getInteractionContent($data['type']);
                //发送im消息
                $imServer = new ImHandleService();
                $imSendArr[]= User::query()->where('id',$data['receive_user_id'])->value('account');
                $fromAccount = User::query()->where('id',$data['user_id'])->value('account');
                $imMessage= $imServer->imSendMessage($fromAccount,$imSendArr,3,$contentStr);
                if(!$imMessage){
                    throw new \Exception("发送im粉丝团消息失败4");
                }
            }
            DB::commit();
            $this->resDate['msg'] = '添加成功';
            return $this->resDate;
        } catch (\Exception $e) {
            DB::rollBack();
            $this->resDate['code'] = 50002;
            $this->resDate['msg'] = $e->getMessage();
            Log::info('互动消息--'.$e->getMessage(),$data);
            return $this->resDate;
        }
    }

    /**
     * 是否存在数据
     * @param $type //类型
     * @param int $video_id //视频id
     * @param int $comment_id //评论id
     * @return bool
     */
    public static function isConfirm($type, $video_id = 0, $comment_id = 0, $replayId = 0)
    {
        $model = new MessageInteract();
        $query = $model::query();
        $query->where('type', $type);
        if ($type == 2) {
            $query->where('video_id', $video_id);
        } elseif ($type == 3) {
            $query->where('video_comment_id', $comment_id);
        } elseif ($type == 5) {
            $query->where('reply_id', $replayId);
        }
        return $query->exists();
    }

    /**
     * 删除数据
     * @param $type
     * @param int $video_id
     * @param int $comment_id
     * @return mixed
     */
    public static function delConfirm($type, $video_id = 0, $comment_id = 0, $replayId = 0)
    {
        $model = new MessageInteract();
        $query = $model::query();
        $query->where('type', $type);
        if ($type == 2) {
            $query->where('video_id', $video_id);
        } elseif ($type == 3) {
            $query->where('video_comment_id', $comment_id);
        } elseif ($type == 5) {
            $query->where('reply_id', $replayId);
        }
        return $query->delete();
    }

    /**
     * 点赞和评论数记录表
     * @param $user_id //操作用户id
     * @param $type // 类型 2 or 3
     * @param int $video_id
     * @param int $comment_id
     * @return bool
     */
    public static function isVideoRecord($user_id, $type, $video_id = 0, $comment_id = 0)
    {
        $model = new MessageInteractRecord();
        $query = $model::query();
        $query->where('user_id', $user_id);
        $query->where('type', $type);
        if ($type == 2) {//作品
            $query->where('video_id', $video_id);
        } else if ($type == 3) {//评论点赞
            $query->where('video_comment_id', $comment_id);
        }
        $flag = $query->exists();
        if ($flag) {
            return false;
        } else {
            $flight = new MessageInteractRecord();
            $flight->user_id = $user_id;
            $flight->type = $type;
            $flight->video_id = $video_id;
            $flight->video_comment_id = $comment_id;
            if (!$flight->save()) {
                return false;
            }
            return true;
        }
    }


    /**
     * 发送消息话术 1.0
     * @param $type 1:抵制低俗公告,2:视频通知,3:奖杯到账通知,4:兑换通知,5:提现通知 6:课程金到账通知
     * @param int $num 金额
     *
     * @return array
     */
    public static function messageTemplate($type, $num = 0, $data = [])
    {
        $ini['type'] = $type;
        $ini['is_show'] = 0;
        $ini['is_delete'] = 0;
        $ini['status'] = 1;
        $cateData = MessageCategory::where($ini)->orderBy('id', 'desc')->get();
        if (count($cateData)) {
            $content = '';
            $cateData = $cateData->toArray();
            foreach ($cateData as $kk => $vv) {
                if ($type == 2) {//视频通知
                    $content = str_replace('X', $data['content'], $vv['category_content']);
                    $content = str_replace('TIME', $data['time'], $content);
                    $cateData[$kk]['category_content'] = $content;
                    unset($content);
                } else {
                    if (strpos($vv['category_content'], "X")) {
                        $cateData[$kk]['category_content'] = str_replace('X', $num, $vv['category_content']) ?? "";
                    }
                }
            }
        }
        return $cateData;
    }

    /**
     * @param $msgType
     * @param $fromAccount
     * @param $account
     * @param $data
     * @return bool
     */
    public static function sendMessage($msgType, $fromAccount, $account, $data)
    {
        try {
            //推送消息
            $model = new ImComp();
            $res = $model->systemMessage($msgType, $fromAccount, $account, $data);

            if (!$res) {
                return false;
            }
            return true;
        } catch (\Exception $e) {
            Log::info('推送消息失败:' . $e->getMessage());
            return false;
        }
    }

    /**
     * 发送消息话术 2.0
     * @param $type
     * @param int $num 金额
     *
     * @return array
     */
    public static function messageTemplateTwo($type, $num = 0)
    {
        $ini['type'] = $type;
        $ini['is_show'] = 0;
        $ini['is_delete'] = 0;
        $ini['status'] = 1;
        $cateData = MessageCategory::where($ini)->orderBy('id', 'desc')->first();
        if ($cateData) {
            $cateData = $cateData->toArray();
            if (strpos($cateData['category_content'], "X") !== false) {
                $cateData['category_content'] = str_replace('X', $num, $cateData['category_content']);
            }
        }
        return $cateData;
    }

    /**
     * 发送系统消息整合 2.0版  --多个参数
     * @param  $data['userId'] 用户id
     * @param  $data['type'] //消息分类所属的类型
     *  '1'=>'抵制低俗公告',       '2'=>'视频通知',           '3'=>'奖杯到账通知',    '4'=>'兑换通知',
     *  '5'=>'提现成功通知',       '6'=>'零钱到账通知',        '7'=>'自定义消息',      '8'=>'公会邀约',
     *  '9'=>'达人同意邀约',       '10'=>'MCN合同签署完成',    '11'=>'合集通知',       '12'=>'服务商资质审核拒绝',
     *  '13'=>'服务商合同签署完成', '14'=>'商户邀约',          '15'=>'服务者同意邀约',  '16'=>'服务者拒绝邀约',
     *  '17'=>'MCN资质审核拒绝',   '18'=>'达人拒绝邀约',      '19'=>'达人退出工会',   '20'=>'服务者资质审核同意',
     *  '21'=>'服务者资质审核拒绝'  '22'=>'MCN/服务商提现通过','23'=>'MCN/服务商提现拒绝',
     *  '24'=>'MCN资质审核同意',   '25'=>'服务商资质审核同意', '26'=>'服务下架', '27'=>'提现失败通知'
     *  '28'=>'举报成功反馈',      '29'=>'举报失败反馈',      '30'=>'被成功举报用户反馈',,'31'=>'服务退款驳回描述','32'=>'店铺关闭审核通过',
     *  '33'=>'店铺关闭审核通过',   '34'=>'店铺关闭审核拒绝'   '35'=>'商户解除服务者','36'=>'用户购买能量包','37'=>'到达预约地点',
     * @param  $data['X'] $data['Time']  //变量名称替换X
     * @param string $data['url']        //跳转地址
     * @param int $data['cateType']      //消息的发送类型 1=单发 2=群发
     * @param int $data['missId']       //群发消息的id
     * @param int $data['pushTime']    //群发消息的推送时间
     */
    public function pushSysMessage($data){
        $userId    = $data['userId'];
        $type      = $data['type'];
        $url       = $data['url'] ?? '';
        $cateType  = $data['cateType'] ?? 1;
        $missId    = $data['missId'] ?? 0;
        $pushTime  = $data['pushTime'] ?? 0;
        $jsonData  = $data['json_data'] ?? '';
        $mechanismId = $data['mcnId'] ?? 0;
        $isSendIm    =  1;
        if(isset($data['notSendIm'])){
            $isSendIm    =  0;
        }
        $ini['type']      = $type;
        $ini['is_show']   = 0;
        $ini['is_delete'] = 0;
        $ini['status']    = 1;
        $cateData = MessageCategory::where($ini)->orderBy('id', 'desc')->first();
        if ($cateData) {
            $cateData = $cateData->toArray();
            //替换变量里面的Y Z
            if(isset($data['X'])){
                if(strpos($data['X'],'Y') !== false){//存在Y的情况，替换Y
                    $data['X'] = str_replace('Y','{zhiyuan1}',$data['X']);
                }
                if(strpos($data['X'],'Z') !== false){//存在Z的情况，替换Z
                    $data['X'] = str_replace('Z','{zhiyuan2}',$data['X']);
                }
            }
            if(isset($data['Y'])){
                if(strpos($data['Y'],'Z') !== false){//存在Z的情况，替换Z
                    $data['Y'] = str_replace('Z','{zhiyuan2}',$data['Y']);
                }
            }
            if ((strpos($cateData['category_content'], "X") !== false) &&  isset($data['X'])) {
                $cateData['category_content'] = str_replace('X', $data['X'], $cateData['category_content']);
            }
            if ((strpos($cateData['category_content'], "Y") !== false) && isset($data['Y'])) {
                $cateData['category_content'] = str_replace('Y', $data['Y'], $cateData['category_content']);
            }
            if ((strpos($cateData['category_content'], "Z") !== false) && isset($data['Z'])) {
                $cateData['category_content'] = str_replace('Z', $data['Z'], $cateData['category_content']);
            }
            if ((strpos($cateData['category_content'], "TIME") !== false) && isset($data['TIME'])) {
                $cateData['category_content'] = str_replace('TIME', $data['TIME'], $cateData['category_content']);
            }
            //替换回去Y Z
            if(strpos($cateData['category_content'],'{zhiyuan1}') !== false){//替换回去Y
                $cateData['category_content'] = str_replace('{zhiyuan1}','Y',$cateData['category_content']);
            }
            if(strpos($cateData['category_content'],'{zhiyuan2}') !== false){//替换回去Z
                $cateData['category_content'] = str_replace('{zhiyuan2}','Z',$cateData['category_content']);
            }
            Log::info("模板内容检测1--".$userId,$cateData);
            sleep(1);
            DB::beginTransaction();
            try {
                    //消息入库
                    $sysRecord = $this->systemMessageAdd($userId, $cateData['category_title'], $cateData['category_content'], $url, $type, $cateData['id'], $cateType,$missId,$pushTime,$jsonData,$mechanismId);
                    if($sysRecord['code'] != 200){
                        throw new \Exception("发送系统消息失败");
                    }
                    Log::info('发送系统消息入库检测2--'.$sysRecord['msg'].'-用户id-'.$userId);
                    if($isSendIm){
                        //发送im消息
                        $account = User::query()->where('id',$userId)->value('account');
                        Log::info('im发送用户检测3--'.$account);
                        $imServer = new ImHandleService();
                        $imMessage= $imServer->imSendMessage($account,[$account],1,$cateData['category_content']);
                        Log::info('消息发送结果:'.$account.',步骤4',['result'=>$imMessage]);
                        if(!$imMessage){
                            throw new \Exception("发送Im系统消息失败");
                        }
                    }

                    DB::commit();
                    $this->resDate['msg'] = 'success';
                    return $this->resDate;
            } catch (\Exception $e) {
                    DB::rollBack();
                    $this->resDate['code'] = 50002;
                    $this->resDate['msg'] = $e->getMessage();
                    $messageData['sendData'] = $data;
                    $messageData['code']     =  50002;
                    $messageData['msg']      = $e->getMessage();
                    Log::info("系统消息发送失败-".$userId,$messageData);
                    return $this->resDate;
            }
        }
    }

    /**
     *  向机构服务商发送消息
     * @param $userId //用户id
     * @param $type //类型
     * @param $replaceStr //要替换的变量
     * @param $mechanismId //机构id
     * @return bool
     */
    public static function pushServerData($userId, $mechanismId, $type, $replaceStr,$jsonData='')
    {
        $data = self::messageTemplateTwo($type, $replaceStr);
        $model = new MessageRecord();
        $model->user_id = $userId;
        $model->message_title = $data['category_title'];
        $model->message_content = $data['category_content'];
        $model->category_id = $data['id'];
        $model->type = $type;
        $model->mcn_id = $mechanismId;
        if($jsonData){
            $model->json_data    = json_encode($jsonData);
        }
        if (!$model->save()) {
            return false;
        }

        return true;
    }


}
